package com.gitee.huanminabc.utils_common.base;

import com.gitee.huanminabc.jcommon.test.PathUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import sun.misc.Launcher;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.util.Enumeration;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

/**
 * 此类用于获取当前项目的信息，包括项目jar，pom.xml，MANIFEST.MF 执行环境等信息
 * <p>
 * 会自动适配IDEA和JAR启动
 * IDEA： 只有projectEnvironment和model可用
 * JAR： projectJarName，jarPath，projectEnvironment，manifest，model都是可以用的
 */
public class ProjectInfo {
    //当前项目的绝对路径
    public static String HOME;

    // jar包名: xxx.jar
    public static String PROJECT_JAR_NAME;
    //当前jar的全路径
    public static String JAR_PATH;


    //执行环境,JAR和IDEA
    public static String PROJECT_ENVIRONMENT;
    //这个只有在项目打包后jar里的MANIFEST.MF信息
    public static Manifest MANIFEST;
    //这个是项目的pom.xml信息
    public static Model MODEL;

    static {
        try {
            ProjectInfo.init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * C:\Users\3426154361_79083\AppData\Local\JetBrains\IntelliJIdea2023.3\captureAgent\debugger-agent.jar
     * 初始化
     * 1.获取当前项目jar包的全路径
     * 2.获取当前项目jar包的MANIFEST.MF信息
     * 3.获取当前项目jar包的pom.xml信息
     * 如果是IDEA启动那么Shorten command line:必须是jar manifest 方式启动 否则会爆zip异常
     */
    private static void init() {
        HOME = PathUtil.getCurrentProjectAbsolutePath();

        try {
            //识别当前执行java启动参数中的java.class.path,如果包含jetBrainsApp,则认为是IDEA启动
            String[] args = System.getProperty("java.class.path").split(";");
            for (String arg : args) {
                if (arg.contains("IDEA")||arg.contains("jetBrainsApp")||arg.contains("JetBrains")||arg.contains("IntelliJIdea")||arg.contains("IntelliJ")) {
                    PROJECT_ENVIRONMENT = "IDEA";
                    break;
                } else {
                    PROJECT_ENVIRONMENT = "JAR";
                }
            }

            if (PROJECT_ENVIRONMENT.equals("JAR")) {
                PROJECT_JAR_NAME = ManagementFactory.getRuntimeMXBean().getClassPath();
                //拼接jar的全路径
                JAR_PATH = HOME + File.separator + PROJECT_JAR_NAME;
                readJar();
            } else {
                readTarget();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static void readJar()  {
        File file = new File(JAR_PATH);
        try (JarFile jarFile = new JarFile(file)) {
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry jarEntry = entries.nextElement();
                if ("META-INF/MANIFEST.MF".equalsIgnoreCase(jarEntry.getName())) {
                    InputStream inputStream = jarFile.getInputStream(jarEntry);
                    MANIFEST = new Manifest(inputStream);
                }
                if (jarEntry.getName().endsWith("pom.xml")) {
                    // 创建Maven模型对象
                    MavenXpp3Reader reader = new MavenXpp3Reader();
                    InputStream inputStream = jarFile.getInputStream(jarEntry);
                    // 读取POM文件
                    MODEL = reader.read(inputStream);
                    break;
                }
            }
        } catch (IOException | XmlPullParserException e) {
            throw new RuntimeException(e);
        }
    }

    private static void readTarget() {
        //====================pom读取
        try {
            File file = new File(HOME, "pom.xml");
            FileReader reader = new FileReader(file);
            MODEL = new MavenXpp3Reader().read(reader);
        } catch (IOException | XmlPullParserException e) {
            throw new RuntimeException(e);
        }


    }

    private static String getCodeSourcePath() {
        return StringUtils.substringBefore(getLuanchPath(), "/target/classes");
    }

    private static String getLuanchPath() {
        return Launcher.getLauncher().getClassLoader().getResource("").getPath();
    }


    public static String show() {
        return "ProjectInfo{HOME:" + HOME + " ,projectJarName:" + PROJECT_JAR_NAME + ", jarPath:" + JAR_PATH + ", projectEnvironment:" +
                PROJECT_ENVIRONMENT + ", manifest:" + MANIFEST.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_TITLE) + ", model:" + MODEL.getArtifactId() + " }";
    }
}
